1486D - Max Median - CodeForces Solution


binary search data structures dp *2100

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=1e6+10;
const int mod=1e9+7;
int n,m,b[N],c[N];
struct node{
	int l,r,val,lazy;
}a[N<<2];
void build(int p,int l,int r){
	a[p].l=l;a[p].r=r;a[p].lazy=-1;a[p].val=0x3f3f3f3f;
	if(l==r)return;
	int mid=l+r>>1;
	build(p*2,l,mid);
	build(p*2+1,mid+1,r);
}
void pushdown(int p){
	if(a[p].l!=a[p].r){
		int mid=a[p].l+a[p].r>>1;
		a[p*2].val=a[p].lazy*(mid-a[p].l+1);
		a[p*2+1].val=a[p].lazy*(a[p].r-mid);
		a[p*2].lazy=a[p*2+1].lazy=a[p].lazy;
	}
	a[p].lazy=-1;
}
void change(int p,int l,int r,int x){
	if(l<=a[p].l&&r>=a[p].r){
		a[p].val=x*(a[p].r-a[p].l+1);
		a[p].lazy=x;
		return;
	}
	if(a[p].lazy!=-1)pushdown(p);
	int mid=a[p].l+a[p].r>>1;
	if(l<=mid)change(p*2,l,r,x);
	if(r>mid)change(p*2+1,l,r,x);
	a[p].val=a[p*2].val+a[p*2+1].val;
}
int query(int p,int x){
	if(a[p].l==a[p].r)return a[p].val;
	if(a[p].lazy!=-1)pushdown(p);
	int mid=a[p].l+a[p].r>>1;
	if(x<=mid)return query(p*2,x);
	else return query(p*2+1,x);
}
int check(int x){
	for(int i=1;i<=n;i++){
		if(b[i]>=x)c[i]=1;
		else c[i]=-1;
	}
	for(int i=1;i<=n;i++)c[i]+=c[i-1];
	build(1,1,n*2+10);
	int mx=0;
	for(int i=n;i>=0;i--)change(1,c[i]+1+n,n*2,i);
	for(int i=1;i<=n;i++){
		int r=i,l=query(1,c[i]+n);
		mx=max(mx,r-l);
	}
	return mx>=m;
}
signed main(){
	ios::sync_with_stdio(false);cin.tie(0);
	cin>>n>>m;
	for(int i=1;i<=n;i++)cin>>b[i];
	int l=1,r=n;
	while(l<r){
		int mid=l+r+1>>1;
		if(check(mid))l=mid;
		else r=mid-1;
	}
	cout<<l<<'\n';
}


Comments

Submit
0 Comments
More Questions

74. Search a 2D Matrix
71. Simplify Path
62. Unique Paths
50. Pow(x, n)
43. Multiply Strings
34. Find First and Last Position of Element in Sorted Array
33. Search in Rotated Sorted Array
17. Letter Combinations of a Phone Number
5. Longest Palindromic Substring
3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome
1092. Shortest Common Supersequence
1044. Longest Duplicate Substring
1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence
42. Trapping Rain Water
32. Longest Valid Parentheses
Cutting a material
Bubble Sort
Number of triangles
AND path in a binary tree
Factorial equations